//
//  RMLoginViewController.m
//  rmplanner
//
//  Created by cs321ga3 on 7/08/12.
//  Copyright (c) 2012 BOSS Systems. All rights reserved.
//

#import "RMLoginViewController.h"
#import "RMFirstViewController.h"
#import <CommonCrypto/CommonDigest.h>

@interface RMLoginViewController ()

- (void)preLogin;
- (NSString *)hash:(NSString *)str;

@end

@implementation RMLoginViewController

@synthesize username, logo, password, retData, uid, indicator;

static BOOL usingSavedCredentials = NO;
static UIAlertView* loadView;

#pragma mark UIViewController functions

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
	{
		CGRect frame = username.frame;
		frame.size.height = frame.size.height * 2;
		username.frame = frame;
	
		frame = password.frame;
		frame.size.height = frame.size.height * 2;
		password.frame = frame;
	}
	
	// if credentials are stored, autofill
	if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"credentials"] boolValue])
	{
		usingSavedCredentials = YES;
		[self preLogin];
	}
	else
	{
		usingSavedCredentials = NO;
	}
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
	    return (interfaceOrientation == UIInterfaceOrientationPortrait);
	} else {
	    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
	}
}

#pragma mark Interface Builder Actions

- (IBAction)checkLogin
{
	// check login credentials, then enter the application. Current code is a placeholder for testing purposes
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/Server/Login.php"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	NSData* data = [[NSString stringWithFormat:@"user=%@&pass=%@", username.text, [self hash:password.text]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSAssert((connection != nil), @"Could not connect");
	
	loadView = [[UIAlertView alloc] init];
	loadView.title = @"Logging in...";
	loadView.frame = CGRectMake(110, 20, 50, 50);
	indicator = [[UIActivityIndicatorView alloc] init];
	indicator.frame = CGRectMake(120, 45, 40, 40);
	[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[loadView addSubview:indicator];
	[loadView show];
	[indicator startAnimating];
}

- (void)preLogin
{
	// check login credentials, then enter the application. Current code is a placeholder for testing purposes
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/confirmCredentials"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	NSData* data = [[NSString stringWithFormat:@"user=%@&pass=%@&devtoken=%@", [[NSUserDefaults standardUserDefaults] valueForKey:@"user"], [[NSUserDefaults standardUserDefaults] valueForKey:@"password"], [[NSUserDefaults standardUserDefaults] valueForKey:@"devToken"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	NSAssert((connection != nil), @"Could not connect");
	
	loadView = [[UIAlertView alloc] init];
	loadView.title = @"Checking credentials...";
	loadView.frame = CGRectMake(110, 20, 50, 50);
	indicator = [[UIActivityIndicatorView alloc] init];
	indicator.frame = CGRectMake(120, 45, 40, 40);
	[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[loadView addSubview:indicator];
	[loadView show];
	[indicator startAnimating];
}

#pragma mark UITextFieldDelegate methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	if (textField == username)
	{
		[textField resignFirstResponder];
		[password becomeFirstResponder];
	}
	else
	{
		[textField resignFirstResponder];
		[self checkLogin];
	}
	return YES;
}

#pragma mark NSURLConnection delegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	connection = nil;
	NSString* response = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
	
	[loadView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	
	if (!usingSavedCredentials)
	{
		if (![response isEqualToString:@"0"])
		{
			// show an action sheet asking if you want credentials to be stored, if they haven't been already
			NSScanner* scanner = [[NSScanner alloc] initWithString:response];
			int value = 0;
			[scanner scanInt:&value];
			uid = value;
			[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"credentials"];
			[[NSUserDefaults standardUserDefaults] setValue:username.text forKey:@"user"];
			[[NSUserDefaults standardUserDefaults] setValue:[self hash:password.text] forKey:@"password"];
			[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Notify"];
			[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge];
			username.text = @"";
			password.text = @"";
			[self performSegueWithIdentifier:@"Login" sender:self];
		}
		else
		{
			NSLog(@"%@\n", response);
			// invalid combination, display an error alert and re-prompt for credentials
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Invalid login" message:@"Username/password combination invalid" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
			username.text = @"";
			password.text = @"";
		}
	}
	else
	{
		if ([response isEqualToString:@"fail"])
		{
			username.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"user"];
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Stored credentials could not be validated. Please log in again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			usingSavedCredentials = NO;
			[alertView show];
		}
		else
		{
			[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Notify"];
			[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge];
			uid = [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"];
			usingSavedCredentials = NO;
			[self performSegueWithIdentifier:@"Login" sender:self];
		}
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	[loadView dismissWithClickedButtonIndex:0 animated:YES];
	[indicator stopAnimating];
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to authentication server failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

#pragma mark Segue functions

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
	if ([[segue identifier] isEqualToString:@"Login"])
	{
		[[NSUserDefaults standardUserDefaults] setInteger:uid forKey:@"uid"];
	}
}

#pragma mark Hash function

- (NSString *)hash:(NSString *)str;
{
	// place the string into a UTF-8 c-string, then hash it
	const char* ptr = [str UTF8String];
	unsigned char md5buffer[CC_MD5_DIGEST_LENGTH];
	CC_MD5(ptr, strlen(ptr), md5buffer);
	
	// place the hashed c-string into a new NSString
	NSMutableString* output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
	for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
		[output appendFormat:@"%02x", md5buffer[i]];
	
	// return the string object
	return output;
}

@end
